package com.uft.controller;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.uft.model.dao.ConfigPropertyDAO;
import com.uft.model.dao.ProfileDAO;
import com.uft.model.entity.Profile;
import com.uft.model.entity.ProfilePreferences;
import com.uft.remote.UftRemote;
import com.uft.service.WasService;




@Controller
public class ProfileController {
	
	 @Autowired
	 private ProfileDAO profileDao;
	 @Autowired
	 private ConfigPropertyDAO configPropertyDAO;
	 @Autowired
	 private WasService wasService;
	 private  static Logger  logger = Logger.getLogger(ProfileController.class);
	
	 @PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/getProfileList", method = RequestMethod.POST)
	@ResponseBody
    public String getProfileList(HttpServletRequest request) {
		
		String result="";
		List<Profile> profileList=new ArrayList<Profile>();
		try{
			profileList=profileDao.getAllProfiles();
			ObjectMapper mapper = new ObjectMapper();
			String listData=mapper.writeValueAsString(profileList);
			logger.debug("List dat: "+listData);
			result="{\"Result\":\"OK\",\"Records\":"+listData+"}";
		}
		catch(Exception ex){
			result="{\"Result\":\"ERROR\",\"Message\":\""+ex.getMessage()+"\"}";
			ex.printStackTrace();
		}
		
		return result;
	}
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/addProfile", method = RequestMethod.POST)
	@ResponseBody
	public String addProfile(Profile profileBean,HttpServletRequest request){
		String result="";
		try{
			//Profile profileBean= getBeanFromRequest(request);
			logger.debug("profileName: Add new  "+profileBean.getProfileName());
			profileDao.addProfile(profileBean);
			ObjectMapper mapper = new ObjectMapper();
			String listData=mapper.writeValueAsString(profileBean);
			result="{\"Result\":\"OK\",\"Record\":"+listData+"}";
		}catch(Exception ex){
			result="{\"Result\":\"ERROR\",\"Message\":\""+ex.getMessage()+"\"}";
			ex.printStackTrace();
			
		}
		logger.debug(result);
		return result;
	}
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/updateProfile", method = RequestMethod.POST)
	@ResponseBody
	public String updateProfile(Profile profileBean,HttpServletRequest request){
		String result="";
		try{
			//Profile profileBean= getBeanFromRequest(request);
			logger.debug("profileName: "+profileBean.getProfileName());
			profileDao.updateProfile(profileBean);
			result="{\"Result\":\"OK\"}";
		}catch(Exception ex){
			result="{\"Result\":\"ERROR\",\"Message\":\""+ex.getMessage()+"\"}";
			ex.printStackTrace();
			
		}
		logger.debug(result);
		return result;
		
	}
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/updateProfilePreference", method = RequestMethod.POST)
	@ResponseBody
	public String updateProfilePreference( ProfilePreferences profilePref ,HttpServletRequest request){
		String result="";
		try{
			//ProfilePreferences profilePref= getProfilePreferenceBeanFromRequest(request);
			//if(profilePref.getPrefId() == null){
			//	return "{\"Result\":\"ERROR\",\"Message\":\"Preference ID is null.. Can't add\"}";
			//}
			logger.debug("profilePref: "+profilePref.getPrefId());
			profileDao.updateProfilePreference(profilePref);
			result="{\"Result\":\"OK\"}";
		}catch(Exception ex){
			result="{\"Result\":\"ERROR\",\"Message\":\""+ex.getMessage()+"\"}";
			ex.printStackTrace();
			
		}
		logger.debug(result);
		return result;
		
	}
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/deleteProfile", method = RequestMethod.POST)
	@ResponseBody
	public String deleteProfile(@RequestParam("profileId") int profileId,HttpServletRequest request){
		String result="";
		try{
			
			   logger.debug("profile id to delete: "+profileId);
			   profileDao.deleteProfileById(profileId);
			   configPropertyDAO.deleteAllConfigPropertyByProfileId(profileId);
			   result="{\"Result\":\"OK\"}";
			
		}catch(Exception ex){
			result="{\"Result\":\"ERROR\",\"Message\":\""+ex.getMessage()+"\"}";
			ex.printStackTrace();
			
		}
		logger.debug(result);
		return result;
		
	}
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/getAdminView", method = RequestMethod.GET)
	public ModelAndView getAdminView(HttpServletRequest request,  
            HttpServletResponse response){
		ModelAndView model = new ModelAndView("administration");
		logger.debug("get Admin Vieiw");
		return model;
	}
	
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/testProfileConnection", method = RequestMethod.POST)
	@ResponseBody
	public String testProfileConnection(@RequestParam("profileId") String profileId,HttpServletRequest request){
		String result="";
		try{
		  	logger.debug("profile id : "+profileId);
			 if( wasService.testWasAdminClientConnection(profileId)){
				 result="{\"Result\":\"OK\"}";
			 }else{
				 result="{\"Result\":\"ERROR\",\"Message\":\"Error in Connecting...\"}";
			 }
			   
		}catch(Exception ex){
			result="{\"Result\":\"ERROR\",\"Message\":\""+ex.getMessage()+"\"}";
			ex.printStackTrace();
			
		}
		logger.debug(result);
		return result;
		
	}
	
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/testSSHConnection", method = RequestMethod.POST)
	@ResponseBody
	public String testSSHConnection(@RequestParam("profileId") String profileId,
			@RequestParam("username") String username,
			@RequestParam("password") String password,
			HttpServletRequest request){
		String result="";
		try{
		  	logger.debug("profile id : "+profileId);
		  	 Profile profile= profileDao.getProfileById(Integer.parseInt(profileId));
		  	 UftRemote uftRemote= new UftRemote(profile.getHostname(),username, password, 22);
		  	 
			 if( uftRemote.testSSHConnection()){
				 result="{\"Result\":\"OK\"}";
			 }else{
				 result="{\"Result\":\"ERROR\",\"Message\":\"Error in Connecting...\"}";
			 }
			   
		}catch(Exception ex){
			result="{\"Result\":\"ERROR\",\"Message\":\""+ex.getMessage()+"\"}";
			ex.printStackTrace();
			
		}
		logger.debug(result);
		return result;
		
	}
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/getRuntimeStatistics", method = RequestMethod.POST)
	@ResponseBody
	public String getRuntimeStatistics(HttpServletRequest request){
		String result="";
		
		try{
			List<HashMap<String,String>> rList= wasService.getWasServiceStats();
			ObjectMapper mapper = new ObjectMapper();
			String listData=mapper.writeValueAsString(rList);
			logger.debug("List dat: "+listData);
			result="{\"Result\":\"OK\",\"Records\":"+listData+"}";
		}catch(Exception ex){
			result="{\"Result\":\"ERROR\",\"Message\":\""+ex.getMessage()+"\"}";
			ex.printStackTrace();
		}
		
		return result;
		
	}
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/deleteRuntimeProfile", method = RequestMethod.POST)
	@ResponseBody
	public String deleteRuntimeProfile(@RequestParam("profileId") int profileId,HttpServletRequest request){
		String result="";
		
		try{
			 if(wasService.removeWasAdminClient(String.valueOf(profileId)))
			  { result="{\"Result\":\"OK\"}"; }
			 else
			  { result="{\"Result\":\"ERROR\",\"Message\":\"Error Occured\"}"; }
			 		
		}catch(Exception ex){
			result="{\"Result\":\"ERROR\",\"Message\":\""+ex.getMessage()+"\"}";
			ex.printStackTrace();
		}
		
		return result;
		
	}

	
}
